#include "Sprite.h"

//construtor dessa classe
Sprite::Sprite(string fileName, int x, int y)
{
    this->fileName = fileName;
    this->x = x;
    this->y = y;

    surfaceRotoZoom = NULL;
    angle = 0;
    zoom = 1;

    //carrega a imagem do sprite
    surface = IMG_Load(fileName.c_str());

    //posições do retângulo do sprite
    rectangle.x = x;
    rectangle.y = y;
    rectangle.w = surface->w;
    rectangle.h = surface->h;

    center = NULL;
}

//método que renderiza o sprite
void Sprite::Render(SDL_Surface *screen)
{
    if(center == NULL)
    {
        rectangle.x = x;
        rectangle.y = y;
    }
    else
    {
        if(center == this)
        {
            rectangle.x = 320;
            rectangle.y = 240;
        }
        else
        {
            rectangle.x = x - center->x + 320;
            rectangle.y = y - center->y + 240;
        }
    }

    if((zoom == 1) && (angle == 0))
        SDL_BlitSurface(surface, NULL, screen, &rectangle);
    else
        SDL_BlitSurface(surfaceRotoZoom, NULL, screen, &rectRot);

    rectRotoZoom.x = x;
    rectRotoZoom.y = y;
}

//método que atualiza a posição do sprite
void Sprite::UpdatePos(int x, int y)
{
    this->x = x;
    this->y = y;
}

//método que retorna o retângulo do sprite
SDL_Rect Sprite::GetRect()
{
    rectangle.x = x;
    rectangle.y = y;

    return rectangle;
}

bool Sprite::boxCollidesWith(Sprite *sprite)
{
    SDL_Rect recB = sprite->GetRect();

    int difX = x - recB.x;
    int difY = y - recB.y;

    /*printf("\nDXA=[%d]||DYA=[%d]||DXB=[%d]||DYB=[%d]\n",dXA,dYA,dXB,dYB);
    printf("\nDIFX=[%d]||DIFY=[%d]\n",difX,difY);*/

    if((difX > recB.w) || (-difX > rectangle.w))
        return false;

    if((difY > recB.h) || (-difY < rectangle.h))
        return false;

    return true;
}

void Sprite::setZoom(double zoom)
{
    SDL_FreeSurface(surfaceRotoZoom);
    this->zoom = zoom;
    surfaceRotoZoom = rotozoomSurface(surface, angle, zoom, 0);

    rectRotoZoom.x = x;
    rectRotoZoom.y = y;
    rectRotoZoom.w = surfaceRotoZoom->w;
    rectRotoZoom.h = surfaceRotoZoom->h;
}

void Sprite::setRot(double angle)
{
    SDL_FreeSurface(surfaceRotoZoom);
    this->angle = angle;
    surfaceRotoZoom = rotozoomSurface(surface, angle, zoom, 0);

    rectRot.x = (x - (surfaceRotoZoom->w - surface->w))/2;
    rectRot.y = (y - (surfaceRotoZoom->h - surface->h))/2;
}

void Sprite::setCenter(Sprite *center)
{
    this->center = center;
}
